//Copyright (C) 2010 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

/*
 * WorkPresetsDialog.java
 *
 * Created on Dec 12, 2009, 12:06:04 PM
 */

package org.workplicity.marist.grounds.ui;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.ListModel;
import org.workplicity.util.Logger;

/**
 *
 * @author Ron Coleman
 */
public class WorkPresetsDialog extends javax.swing.JDialog {
    private String[] requiredWork = null;
    private String tag = null;
    private Boolean cancelled = false;

    /** Creates new form WorkPresetsDialog */
    public WorkPresetsDialog(JDialog parent, String fileName,String[] requiredWork,String tag) {
        super(parent, true);
        initComponents();

        this.tag = tag;

        this.requiredWork = removeTags(requiredWork);

        initWith(fileName);
    }

    private void initWith(String fileName) {
        try {
            // Add the requiredWork to the requiredWork list
            InputStream is = getClass().getResourceAsStream(fileName);
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is));

            DefaultListModel presetsModel =
                    (DefaultListModel) presetsList.getModel();

            String line = "";
            while((line = reader.readLine()) != null) {
                presetsModel.addElement(line);
            }

            // Add the required work list
            DefaultListModel requiredModel = (DefaultListModel) this.requiredList.getModel();
            for(int i=0; i < requiredWork.length; i++)
                requiredModel.addElement(requiredWork[i]);

            reader.close();
        }
        catch(Exception e) {
            Logger.log("failed to open presets '"+requiredWork+"':"+e);
        }
    }

    private String[] removeTags(String[] inputs) {
        String[] outputs = new String[inputs.length];

        for(int i=0; i < inputs.length; i++) {
            outputs[i] = inputs[i];

            int indx = inputs[i].indexOf(tag);

            if(indx != -1)
                outputs[i] = inputs[i].substring(0, indx);
        }

        return outputs;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        presetsList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        requiredList = new javax.swing.JList();
        addDescrButton = new javax.swing.JButton();
        removeDescrButton = new javax.swing.JButton();
        moveUpButton = new javax.swing.JButton();
        moveDownButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Work presets:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Required work:");

        cancelButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        presetsList.setModel(new DefaultListModel());
        jScrollPane1.setViewportView(presetsList);

        requiredList.setModel(new DefaultListModel( ));
        jScrollPane2.setViewportView(requiredList);

        addDescrButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/add2.png"))); // NOI18N
        addDescrButton.setToolTipText("Click to add selected description.");
        addDescrButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addDescrButtonActionPerformed(evt);
            }
        });

        removeDescrButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/remove4.png"))); // NOI18N
        removeDescrButton.setToolTipText("Click to remove selected description.");
        removeDescrButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeDescrButtonActionPerformed(evt);
            }
        });

        moveUpButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/small-up15.gif"))); // NOI18N
        moveUpButton.setToolTipText("Click to move up description in priority.");
        moveUpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveUpButtonActionPerformed(evt);
            }
        });

        moveDownButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/small-down16.gif"))); // NOI18N
        moveDownButton.setToolTipText("Click to move down description in priority.");
        moveDownButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveDownButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                        .addGap(83, 83, 83))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                    .addComponent(addDescrButton)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(removeDescrButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveUpButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveDownButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(1, 1, 1)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addDescrButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(removeDescrButton)
                    .addComponent(moveUpButton)
                    .addComponent(moveDownButton))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        ListModel model = this.requiredList.getModel();

        int sz = model.getSize();

        requiredWork = new String[sz];

        for(int i=0; i < sz; i++)
            requiredWork[i] = (String) model.getElementAt(i) + " " + tag;

        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    public Boolean isCanceled() {
        return cancelled;
    }
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        cancelled = true;
        
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void addDescrButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDescrButtonActionPerformed
        DefaultListModel requiredModel = (DefaultListModel) requiredList.getModel();

        Object[] items = presetsList.getSelectedValues();

        for(int i=0; i < items.length; i++) {
            boolean found = false;

            for(int j=0; j < requiredModel.size(); j++) {
                if(items[i].equals(requiredModel.get(j))) {
                    found = true;
                    break;
                }
            }

            if(found)
                continue;
            
            requiredModel.addElement(items[i]);
        }
    }//GEN-LAST:event_addDescrButtonActionPerformed

    private void removeDescrButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeDescrButtonActionPerformed
        String item = (String) requiredList.getSelectedValue();

        if(item == null)
            return;

        int index = requiredList.getSelectedIndex();

        DefaultListModel requiredModel = (DefaultListModel) requiredList.getModel();

        requiredModel.removeElement(item);

        if(requiredModel.size() != 0) {
            if(index == requiredModel.size())
                index--;
            requiredList.setSelectedIndex(index);
        }
    }//GEN-LAST:event_removeDescrButtonActionPerformed

    private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed
        String item = (String) requiredList.getSelectedValue();
        
        int targetIndex = requiredList.getSelectedIndex();

        if(item == null || targetIndex == 0)
            return;

        DefaultListModel requiredModel = (DefaultListModel) requiredList.getModel();

        requiredModel.removeElement(item);

        requiredModel.add(targetIndex-1, item);

        requiredList.setSelectedIndex(targetIndex-1);
    }//GEN-LAST:event_moveUpButtonActionPerformed

    private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed
        String item = (String) requiredList.getSelectedValue();

        int targetIndex = requiredList.getSelectedIndex();

        DefaultListModel requiredModel = (DefaultListModel) requiredList.getModel();

        if(item == null || targetIndex == (requiredModel.getSize() - 1))
            return;

        requiredModel.removeElement(item);

        requiredModel.add(targetIndex+1, item);

        requiredList.setSelectedIndex(targetIndex+1);
    }//GEN-LAST:event_moveDownButtonActionPerformed

    /**
     * Get the preset descriptions.
     * @return String array, null if there aren't any
     */
    public String[] getSelections() {
        return requiredWork;
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    Logger.log(e.toString());
                }
                String[] requiredWork = {"Check for garbage.", "Check and weed beds as needed.", "Spray Roundup in your area as needed and record usage." };
                WorkPresetsDialog dialog = new WorkPresetsDialog(new JDialog(), "/spring.txt",requiredWork,"[sp]");
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addDescrButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton moveDownButton;
    private javax.swing.JButton moveUpButton;
    private javax.swing.JList presetsList;
    private javax.swing.JButton removeDescrButton;
    private javax.swing.JList requiredList;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

}
